import React from 'react';
import { Menu, message } from 'antd';
import { BUSINESS_INF0 } from 'Constants/config';
import { connect } from 'react-redux';
import Api from 'Utils/api';
import './../../VideoSysPage/index.scss';


const { SubMenu } = Menu;
const limit = 1000;

let isInitFinished = false;//视频插件是否加载完成
class VideoSysPage extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      business: [],
      startIndex: 1,
      endIndex: limit,
      jsession: sessionStorage.getItem('jsession') || '',
      vehicles: [],
      initType: props.params.type,
      initId: props.params.id,
      selectCode: ''
    };
    // 企业监控
    this.insertBusinessObj = ::this.insertBusinessObj;
    this.setInitBusiness = ::this.setInitBusiness;
    this.handleBusiness = ::this.handleBusiness;
    this.closeBusinessResource = ::this.closeBusinessResource;
    // 无人机
    this.initVehicleVideoPlugin = ::this.initVehicleVideoPlugin;
    this.initVehicleFlash = ::this.initVehicleFlash;
    this.handlevehicle = ::this.handlevehicle;
  }
  componentWillUnmount() {
    this.closeBusinessResource();
    clearTimeout(this.timer);
    if (window.player && this.state.initType === 'vehicle') {
      window.player.stopVideo(0); // 停止播放无人机
    }
  }
  componentDidMount() {
    const { initType } = this.state;
    if (initType === 'vehicle') {
      this.initVehicleVideoPlugin();
      this.initVehicleFlash();
    }
    if (initType === 'task') {
      this.getTaskDetail();
      this.insertBusinessObj();
    }
    if (initType === 'map') {
      this.getBusinessDetail();
      this.insertBusinessObj();
    }
  }
  getBusinessDetail() {
    const api = new Api({
      method: 'GET',
      path: `/enterprise_details/enterprise_info/${this.state.initId}`,
      success: (res) => {
        this.setState({
          business: res.sun_kitchens,
        }, () => {
          this.setInitBusiness();
        });
      }
    });
    api.run();
  }
  getTaskDetail() {
    const api = new Api({
      method: 'GET',
      path: `/tasks/${this.state.initId}`,
      success: (res) => {
        console.log(res);
        this.setState({
          business: res.sun_kitchens,
        }, () => {
          this.setInitBusiness();
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  // 企业监控
  // insert object
  closeBusinessResource() {
    preview.StopPreview(-1);
  }
  insertBusinessObj() {
    document.getElementById('business-video').innerHTML = `
     <object classid="clsid:BE020CC9-521F-4641-85E1-3B631B7ADDD9" id="preview" width="100%" height="100%"  name="preview" >
       <PARAM NAME="Ip" VALUE="60.12.65.115"/>
       <PARAM  NAME="UserName " VALUE="admin"/>
       <PARAM  NAME="PrivilegeCode" VALUE="0401,0402,"/>
    </object> `;
  }
  // init && login
  setInitBusiness() {
    // 判断海康是否已经登录
    const param = `
    <?xml version="1.0" encoding="utf-8"?><LoginInfo><LoginType>2</LoginType><SynLogin>1</SynLogin><IP>${BUSINESS_INF0.ServerIP}</IP><Port>${BUSINESS_INF0.Port}</Port><UserName>${BUSINESS_INF0.UserName}</UserName><Password>${BUSINESS_INF0.PWD}</Password></LoginInfo>`;
    const res = preview.LoginPlat(param);
    if (res !== 0) {
      console.log('登录海康失败');
    }
    preview.SetLayoutType(1); // 设置窗格数
  }
  // 无人机
  //初始化视频插件
  initVehicleVideoPlugin() {
    //视频插件初始化参数
    const params = {
      allowFullscreen: 'true',
      allowScriptAccess: 'always',
      bgcolor: '#ffffff',
      wmode: 'transparent'
    };
    //初始化flash
    const self = this;
    swfobject.embedSWF('static/player.swf', 'cmsv6flash', '100%', '100%', '11.0.0', null, null, params, null, (e) => {
      window.player = e.ref;
      setTimeout(() => { self.initVehicleFlash(); }, 2000);
    });
  }
  initVehicleFlash() {
    const self = this;
    if (window.player === null || !window.player.setWindowNum) {
      this.timer = setTimeout(() => { self.initVehicleFlash(); }, 5000);
      message.warn('初始化flash失败');
    } else {
      //设置视频插件的语言
      window.player.setLanguage('http://211.162.125.99:8080/808gps/open/player/cn.xml');
      //先将全部窗口创建好
      window.player.setWindowNum(36);
      //再配置当前的窗口数目
      window.player.setWindowNum(1);
      //设置视频插件的服务器
      window.player.setServerInfo('211.162.125.99', '6605');
      isInitFinished = true;
      this.handlevehicle(this.state.initId);
    }
  }
  handlevehicle(deId) {
    if (isInitFinished) {
      console.log('test');
      // window title
      window.player.setVideoInfo(0, `无人机${deId}实时视频`);
      //play
      window.player.startVideo(0, this.state.jsession, deId, 0, 1, true);
      // buffer
      window.player.setBufferTime(0, 2);
    }
  }
  //public for business && vehicles
  change(item) {
    const type = item.item.props.type;
    this.setState({
      selectCode: item.key
    });
    if (type === 'business') {
      if (window.player) {
        window.player.stopVideo(0); // 停止播放
      }
      this.handleBusiness(item.item.props.code);
    }
  }
  handleBusiness(code) {
    console.log(code);
    const _param = `<?xml version="1.0" encoding="UTF-8"?><Preview><CamIndexCode>${code}</CamIndexCode></Preview>`;
    preview.StartPreview(_param);
  }
  render() {
    const { business, initId, initType, selectCode } = this.state;
    const defaultSelect = initType === 'vehicle' ? 'vehicleItem' : selectCode;
    return (
      <div className="video-sys-wrapper" >
        <div className="video-sys-container">
          <div className="video-wrap">
            <div className="video">
              <div id="business-video" />
              <div className="vehicle-wrap">
                <div id="cmsv6flash" />
              </div>
            </div>
          </div>
          <div className="side-wrap">
            <div>
              <div className="video-menu">
                <div className="sys-menu">
                  <Menu
                    style={{ width: 240 }}
                    mode="inline"
                    theme="light"
                    onSelect={this.change.bind(this)}
                    defaultOpenKeys={['vehicle', 'business']}
                    selectedKeys={[defaultSelect]}
                  >
                    {
                      initType === 'vehicle' ? <SubMenu key="vehicle" title={<span><img src="images/videoSys/icon_no_people.png" className="menu-icon" alt="无人机" /><span>无人机</span></span>}>
                        {
                          <Menu.Item className="submenu" type="vehicle" key="vehicleItem" >无人机{initId}</Menu.Item>
                        }
                      </SubMenu> : ''
                    }
                    {
                      business.length > 0 && <SubMenu key="business" title={<span><img src="images/videoSys/icon_business_monitor.png" className="menu-icon" alt="企业监控" /><span>企业监控</span></span>}>
                        {
                          business.map(item => (
                            <Menu.Item key={item.camera_code} className="submenu" type="business" code={item.camera_code} status={item.on_line} disabled={!(item.on_line === 1)} >
                              {
                                item.on_line === 1 ? <img src="images/videoSys/icon_on.png" className="video-state" alt="" /> : <img src="images/videoSys/icon_off.png" alt="" className="video-state" />
                              }
                              {item.name}
                            </Menu.Item>
                          ))
                        }
                      </SubMenu>
                    }
                  </Menu>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
function mapStateToProps(state) {
  return {
    ...state.routing,
  };
}

export default connect(mapStateToProps)(VideoSysPage);
